#!/usr/bin/env php
<?php
$SOAR_DIR=getenv("SOAR_DIR");
if(empty($SOAR_DIR)) $SOAR_DIR="/opt/soar";
include "$SOAR_DIR/common/php/soar/soar.inc";

function load_cnfg()
{/*{{{*/
    $svcenv_dir=getenv("SVCENV_DIR");
    if(empty($svcenv_dir))
    {
        print "Error: SVCENV_DIR not set\n";
        return false;
    }
    $svcenv_cnfg=getenv("SVCENV_CNFG");
    if(empty($svcenv_cnfg))
    {
        print "Error: SVCENV_CNFG not set\n";
        return false;
    }
    include $svcenv_cnfg;

    return true;
}/*}}}*/

function call($sock, $cmd)
{/*{{{*/
    $p=strpos($cmd, " ");
    if($p === false)
        $c=$cmd;
    else
        $c=substr($cmd, $p);
    $c=strtoupper($c);
    if(in_array($c, array("EXIT","QUIT","BYE")))
        return "";
    $cmd.="\r\n";
    $res=socket_send($sock, $cmd, strlen($cmd), 0);
    if($res === false || $res == 0)
    {
        printf("Error: send to server fail: %s\n", 
                socket_strerror(socket_last_error()));
        return "";
    }
    $res=socket_recv($sock, $respond, 2048, 0);
    if($res === false || $res == 0)
    {
        printf("Error: recv from server fail: %s\n", 
                socket_strerror(socket_last_error()));
    }
    $respond=trim($respond);
    return $respond;
}/*}}}*/

function main($argv)
{/*{{{*/
    if(load_cnfg() == false)
        return 1;

    $timeout=5;
    $sock=sock::connect("localhost:".cnfg::$agent['monitor_port'],
            $timeout);
    if($sock === false)
    {
        print "Error: connect to SVCENV fail\n";
        return 1;
    }

    if(empty($argv[1]))
    {
        $prompt="> ";
        while(1)
        {
            print $prompt;
            $cmd=fgets(STDIN);
            if($cmd === false) break;
            $cmd=trim($cmd);
            $respond=call($sock, $cmd);
            if(empty($respond)) break;
            print $respond."\n\n";
        }
    }
    else
    {
        $respond=call($sock, $argv[1]);
        print $respond."\n\n";
    }

    socket_close($sock);

    return 0;
}/*}}}*/

main($argv);
?>
